#include"chen.h"

static void sig_alarm( int );

void
dg_cli( FILE *fp, int sockfd,  struct sockaddr * pservaddr, socklen_t servlen )
{
	int n;
	char sendline[MAXLINE], recvline[MAXLINE + 1];

	signal( SIGALRM, sig_alarm );

	while ( Fgets( sendline, MAXLINE, fp ) != NULL ) {
		Sendto( sockfd, sendline, strlen( sendline ), 0, pservaddr, servlen );

		alarm( 5 );
		if (  ( n = recvfrom( sockfd, recvline, MAXLINE, 0, NULL, NULL )  ) < 0 ) {
			if ( errno == EINTR )
				fprintf( stderr, "socket time out!" );
			else
				err_sys( "recvfrom error!" );
		} else {
			alarm( 0 );
			recvline[n] = 0;
			Fputs( recvline, stdout );
		}
	}
}

void
dg_cliout( FILE *fp, int sockfd,  struct sockaddr * pservaddr, socklen_t servlen )
{
	int n;
	char sendline[MAXLINE], recvline[MAXLINE + 1];
	struct timeval tv;

	tv.tv_sec = 5;
	tv.tv_usec = 0;

	setsockopt( sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof( tv ) );
	while ( Fgets( sendline, MAXLINE, fp ) != NULL ) {
		Sendto( sockfd, sendline, strlen( sendline ), 0, pservaddr, servlen );

		n = recvfrom( sockfd, recvline, MAXLINE, 0, NULL, NULL );
		if ( n < 0 ) {
			if ( errno == EWOULDBLOCK ) {
				fprintf( stderr, "socket time out!" );
				continue;
			} else
				err_sys( "recvfrom error!" );
		}
			recvline[n] = 0;
			Fputs( recvline, stdout );
	}
}

static void
sig_alarm( int signo )
{
	return;
}
